<?php

class BuyController extends Application_Model_Controller
{
    /**
     * @var null| Application_Model_Mapper
     */
    protected $mapper = null;

    public function preDispatch()
    {
        parent::preDispatch();
        $title = 'Покупки';
        $this->view->headTitle($title);
        $this->view->headScript()->appendFile($this->view->baseUrl() . '/js/buy.js');
        $this->view->headScript()->appendFile($this->view->baseUrl()  . '/js/redactor/redactor.js');
        $this->view->headLink()->appendStylesheet($this->view->baseUrl() . '/js/redactor/css/redactor.css', 'screen');
        $this->mapper = new Application_Model_Mapper(new Application_Model_DbTable_Buy(), new Application_Model_Buy());
        $this->view->topGoods = $this->mapper->getCollection('buy_status > 0', 'buy_status DESC', array('count' => 10, 'start' => 0)); //последние 10 добавленных
        $this->view->tplSidebar = 'buy.phtml';
    }

    public function indexAction()
    {
        $type = $this->_getParam('type');
        $page = $this->_getParam('page', 1);

        $limit['start'] = Application_Model_Mapper::DEFAULT_LIMIT * ($page - 1);
        $limit['count'] = Application_Model_Mapper::DEFAULT_LIMIT;

        $this->view->goods = $this->mapper->getCollection(
            $type ? array('buy_type' => $type) : array(),
            'buy_id DESC',
            $limit
        );

        $this->view->nextPage = (count($this->view->goods) < Application_Model_Mapper::DEFAULT_LIMIT) ? false : $page + 1;
        $this->view->prevPage = ($page == 1) ? false : $page - 1;
        $params = array('page' => $this->view->prevPage);

        if ($type) {
            $params['type'] = $type;
        }

        $this->view->paramsPrevPage = $params;
        $params = array('page' => $this->view->nextPage);

        if ($type) {
            $params['type'] = $type;
        }

        $this->view->paramsNextPage = $params;
        $this->view->types = Application_Model_Buy::getTypes();
    }
}
